package com.framework.bdf4j.comm;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.framework.bdf4j.comm.exception.BaseException;

/**
 * <b>文件名： </b>SpringContextHolder.java<br/>
 * <b>类描述： </b>Spring工具类 ，获取Spring容器中的上下文信息<br/>
 * <p>
 * 使用的时候需要注入到 Spring上下文中，如下设置：<br/>
 * &lt;bean id="springContextHolder" class="com.framework.bdf4j.comm.SpringContextHolder" /&gt;<br/>
 *
 */
public class SpringContextHolder implements ApplicationContextAware {

	private static ApplicationContext context;

	private static void checkApplicationContext() {
		if (context == null) {
			throw new BaseException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder");
		}
	}

	public static ApplicationContext getApplicationContext() {
		checkApplicationContext();
		return context;
	}

	public static <T> T getBean(Class<T> clazz) {
		checkApplicationContext();
		return context.getBean(clazz);
	}

	@SuppressWarnings("unchecked")
	public static <T> T getBean(String name) {
		checkApplicationContext();
		return (T) context.getBean(name);
	}

	@Override
	public void setApplicationContext(ApplicationContext ac) {
		context = ac;
	}

}
